package com.platform.framework.util.pub;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 
 * @author lgy
 * @version 1.0 Json 字符串生成工具类
 *          <P>
 *          传入数扰载体，生成json格式字符串
 *          </p>
 *          全部修改成GSON处理类去处理
 */
@SuppressWarnings("unchecked")
public class JsonUtil {

	private static Logger log = Logger.getLogger(JsonUtil.class);

	/**
	 * 直接输出JSON
	 * 
	 * @param json
	 * @param response
	 */
	public static void write(String json, HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/plain;charset=UTF-8");
		try {
			PrintWriter writer = response.getWriter();
			writer.write(json);
		} catch (IOException e) {
			log.error("JsonUtil类的write方法失败：" + e.getMessage());
			e.printStackTrace();
		}

	}

	/**
	 * 将object转化为Json(gson插件)
	 *
	 * @param object
	 *            可以设置为List<Object> list
	 * @return String
	 */
	public static String objToJson(Object object) {
		try {
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
					.create();
			String jsonStr = gson.toJson(object);
			return jsonStr;
		} catch (Exception e) {
			log.error("objToJson失败：" + e.getMessage());
			throw new RuntimeException(e);
		}

	}

	/**
	 * 从json转成对象
	 * 
	 * @param json
	 * @param typeOfT
	 * @return
	 * @throws com.google.gson.JsonSyntaxException
	 */
	public static <T> T fromJson(java.lang.String json,
			java.lang.reflect.Type typeOfT)
			throws com.google.gson.JsonSyntaxException {
		try {
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
					.create();
			return (T)gson.fromJson(json, typeOfT);
		} catch (Exception e) {
			log.error("fromJson失败：" + e.getMessage() + "\\n转换jsonStr为："
					+ json);
			throw new RuntimeException(e);
		}

	}

	/**
	 * 使用jackson包将集合对象转为Json
	 * 
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static String Object2Json(Object obj) throws Exception {
		String result = "";
		ObjectMapper mapper = new ObjectMapper();
		try {
			mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
			result = mapper.writeValueAsString(obj);

		} catch (Exception e) {
			log.error("Object2Json失败：" + e.getMessage());
			throw new RuntimeException(e);
		}
		return result;
	}

	/**
	 * 使用jackson包json字符串转化为对象
	 * @param jsonStr
	 * @param valueType
	 * @return
	 */
	public static <T> T Json2Object(String jsonStr, Class<T> valueType) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
			return (T)mapper.readValue(jsonStr, valueType);

		} catch (Exception e) {
			log.error("Json2Object失败：" + e.getMessage() + "\\n转换jsonStr为："
					+ jsonStr);
			throw new RuntimeException(e);
		}

	}
	
	/**
	 * 根据target字段在json查找值
	 * @param json
	 * @param target
	 * @return
	 */
	public static String searchJson (String json ,String target,boolean isSearchArray) {
		String result = "";
		Pattern p = null;
		if (isSearchArray) {
			p = Pattern.compile(".*?\""+target+"\":[(.*?)].*");
		} else {
			p = Pattern.compile(".*?\""+target+"\":\"(.*?)\".*");
		}
		
	    Matcher m = p.matcher(json);
	    while(m.find()) {
	      result = m.group();
	    }
		return result;
	}
	
}
